﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ServiceHosting.ServiceRuntime;
using Microsoft.Samples.ServiceHosting.StorageClient;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using UlyssesAgenda.CoreLib;
//using UlyssesAgenda.CoreLib;

namespace UlyssesAgenda.Repositories.Regions
{
    public class RegionRepository : CloudStorageRepositoryBase
    {      
        public RegionRepository(StorageAccountInfo blob, StorageAccountInfo queue, StorageAccountInfo table): base(blob, queue, table)
        {
            InitBlobContainer(RoleManager.GetConfigurationSetting("RegionContainer"));
        }               

        public void DeleteRegion(string filename)
        {
            blobContainer.DeleteBlob(filename);
        }

        public void CreateRegion(RegionFileInfo info, string contentType, byte[] fileBytes)
        {
            string extension = System.IO.Path.GetExtension(info.Filename);
            string trimmedFilename = Path.GetFileName(info.Filename);
            BlobProperties properties = new BlobProperties(trimmedFilename);

            // Create metadata to be associated with the blob
            NameValueCollection metadata = new NameValueCollection();            
            metadata["Submitter"] = info.Submitter;            
            metadata["RegionName"] = info.Name;
            metadata["RegionDescription"] = info.Description;

            properties.Metadata = metadata;
            properties.ContentType = contentType;                        

            // Create the blob
            BlobContents fileBlob = new BlobContents(fileBytes);
            blobContainer.CreateBlob(properties, fileBlob, true);
        }

        public RegionFileInfo[] GetRegions()
        {
            IEnumerable<object> blobs = blobContainer.ListBlobs(string.Empty, false);
            List<RegionFileInfo> regionFiles = new List<RegionFileInfo>();
            foreach (object blobObject in blobs)
            {
                BlobProperties props = blobObject as BlobProperties;
                if (props != null)
                {
                    BlobProperties blobProps = blobContainer.GetBlobProperties(props.Name);
                    NameValueCollection nvc = blobProps.Metadata;
                    regionFiles.Add(new RegionFileInfo()
                    {
                        Name = nvc["RegionName"],
                        Description = nvc["RegionDescription"],
                        Url = props.Uri.ToString(),
                        Filename = blobProps.Name,
                        Submitter = nvc["Submitter"]
                    });
                }
            }
            return regionFiles.ToArray();
        }
    }
}
